package com.example.controller;

import com.example.model.Role;
import com.example.model.Permission;
import com.example.model.SystemConfig;
import com.example.model.OperationLog;
import com.example.service.RoleService;
import com.example.service.PermissionService;
import com.example.service.SystemConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/api")
@Tag(name = "系统管理", description = "角色、权限、配置和日志管理")
public class SystemController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private SystemConfigService systemConfigService;

    // ==================== 角色管理 ====================
    @GetMapping("/admin/roles")
    @Operation(summary = "获取角色列表")
    public ResponseEntity<Page<Role>> getRolesList(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        Pageable pageable = PageRequest.of(page, size, Sort.by("name"));
        Page<Role> roles = roleService.findAllActiveRoles(pageable);
        return ResponseEntity.ok(roles);
    }

    @GetMapping("/admin/roles/{id}")
    @Operation(summary = "获取角色详情")
    public ResponseEntity<Role> getRoleDetail(@PathVariable Long id) {
        return roleService.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping("/admin/roles")
    @Operation(summary = "创建角色")
    public ResponseEntity<Role> createRole(@Valid @RequestBody Role role) {
        Role createdRole = roleService.createRole(role);
        return ResponseEntity.ok(createdRole);
    }

    @PutMapping("/admin/roles/{id}")
    @Operation(summary = "更新角色")
    public ResponseEntity<Role> updateRole(
            @PathVariable Long id,
            @Valid @RequestBody Role role) {

        role.setId(id);
        Role updatedRole = roleService.updateRole(role);
        return ResponseEntity.ok(updatedRole);
    }

    @DeleteMapping("/admin/roles/{id}")
    @Operation(summary = "删除角色")
    public ResponseEntity<Void> deleteRole(@PathVariable Long id) {
        roleService.deleteRole(id);
        return ResponseEntity.ok().build();
    }

    // ==================== 权限管理 ====================
    @GetMapping("/system/permissions")
    @Operation(summary = "获取系统权限列表")
    public ResponseEntity<List<Permission>> getPermissionsList() {
        List<Permission> permissions = permissionService.findAllActivePermissions();
        return ResponseEntity.ok(permissions);
    }

    @PostMapping("/system/permissions")
    @Operation(summary = "创建权限")
    public ResponseEntity<Permission> createPermission(@Valid @RequestBody Permission permission) {
        Permission createdPermission = permissionService.createPermission(permission);
        return ResponseEntity.ok(createdPermission);
    }

    @PutMapping("/system/permissions/{id}")
    @Operation(summary = "更新权限")
    public ResponseEntity<Permission> updatePermission(
            @PathVariable Long id,
            @Valid @RequestBody Permission permission) {

        permission.setId(id);
        Permission updatedPermission = permissionService.updatePermission(permission);
        return ResponseEntity.ok(updatedPermission);
    }

    @DeleteMapping("/system/permissions/{id}")
    @Operation(summary = "删除权限")
    public ResponseEntity<Void> deletePermission(@PathVariable Long id) {
        permissionService.deletePermission(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/admin/roles/{roleId}/permissions")
    @Operation(summary = "获取角色权限")
    public ResponseEntity<Set<Permission>> getRolePermissions(@PathVariable Long roleId) {
        Set<Permission> permissions = roleService.getRolePermissions(roleId);
        return ResponseEntity.ok(permissions);
    }

    @PutMapping("/admin/roles/{roleId}/permissions")
    @Operation(summary = "更新角色权限")
    public ResponseEntity<Map<String, Object>> updateRolePermissions(
            @PathVariable Long roleId,
            @RequestBody Map<String, Object> permissionData) {

        @SuppressWarnings("unchecked")
        List<Long> permissionIds = (List<Long>) permissionData.get("permissionIds");
        Set<Long> permissionIdSet = Set.copyOf(permissionIds);

        roleService.updateRolePermissions(roleId, permissionIdSet);

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "角色权限更新成功");
        return ResponseEntity.ok(response);
    }

    // ==================== 系统配置管理 ====================
    @GetMapping("/admin/config")
    @Operation(summary = "获取系统配置")
    public ResponseEntity<List<SystemConfig>> getSystemConfig() {
        List<SystemConfig> configs = systemConfigService.findAllVisibleConfigs();
        return ResponseEntity.ok(configs);
    }

    @GetMapping("/admin/config/category/{category}")
    @Operation(summary = "根据分类获取配置")
    public ResponseEntity<List<SystemConfig>> getConfigByCategory(@PathVariable String category) {
        List<SystemConfig> configs = systemConfigService.findByCategory(category);
        return ResponseEntity.ok(configs);
    }

    @PutMapping("/admin/config")
    @Operation(summary = "批量更新系统配置")
    public ResponseEntity<Map<String, Object>> updateSystemConfig(@RequestBody Map<String, String> configData) {
        systemConfigService.updateConfigs(configData);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "系统配置更新成功");
        return ResponseEntity.ok(response);
    }

    @PostMapping("/admin/config")
    @Operation(summary = "创建系统配置")
    public ResponseEntity<SystemConfig> createSystemConfig(@Valid @RequestBody SystemConfig config) {
        SystemConfig createdConfig = systemConfigService.createConfig(config);
        return ResponseEntity.ok(createdConfig);
    }

    @PutMapping("/admin/config/{id}")
    @Operation(summary = "更新单个配置")
    public ResponseEntity<SystemConfig> updateSingleConfig(
            @PathVariable Long id,
            @Valid @RequestBody SystemConfig config) {

        config.setId(id);
        SystemConfig updatedConfig = systemConfigService.updateConfig(config);
        return ResponseEntity.ok(updatedConfig);
    }

    @DeleteMapping("/admin/config/{id}")
    @Operation(summary = "删除配置")
    public ResponseEntity<Void> deleteConfig(@PathVariable Long id) {
        systemConfigService.deleteConfig(id);
        return ResponseEntity.ok().build();
    }

    // ==================== 操作日志管理 ====================
    @GetMapping("/admin/logs")
    @Operation(summary = "获取操作日志")
    public ResponseEntity<Page<Map<String, Object>>> getSystemLogs(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String operation,
            @RequestParam(required = false) String username) {
        
        // 这里应该有专门的日志服务，暂时返回空页面
        Pageable pageable = PageRequest.of(page, size);
        Page<Map<String, Object>> emptyPage = Page.empty(pageable);
        return ResponseEntity.ok(emptyPage);
    }

    @GetMapping("/admin/logs/export")
    @Operation(summary = "导出操作日志")
    public ResponseEntity<byte[]> exportSystemLogs(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        // 这里应该实现日志导出逻辑
        String csvContent = "时间,用户,操作,模块,描述\n";
        return ResponseEntity.ok()
                .header("Content-Disposition", "attachment; filename=system_logs.csv")
                .header("Content-Type", "text/csv")
                .body(csvContent.getBytes());
    }

    // ==================== 商家管理 ====================
    @GetMapping("/admin/merchants")
    @Operation(summary = "获取商家列表")
    public ResponseEntity<Page<Map<String, Object>>> getMerchantsList(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Map<String, Object>> emptyPage = Page.empty(pageable);
        return ResponseEntity.ok(emptyPage);
    }

    @GetMapping("/admin/merchants/{id}")
    @Operation(summary = "获取商家详情")
    public ResponseEntity<Map<String, Object>> getMerchantDetail(@PathVariable Long id) {
        Map<String, Object> merchant = new HashMap<>();
        merchant.put("id", id);
        merchant.put("name", "示例商家");
        merchant.put("status", "ACTIVE");
        return ResponseEntity.ok(merchant);
    }

    @PutMapping("/admin/merchants/{id}/approve")
    @Operation(summary = "审批商家")
    public ResponseEntity<Map<String, Object>> approveMerchant(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "商家审批成功");
        return ResponseEntity.ok(response);
    }

    @PutMapping("/admin/merchants/{id}/reject")
    @Operation(summary = "拒绝商家")
    public ResponseEntity<Map<String, Object>> rejectMerchant(
            @PathVariable Long id,
            @RequestBody Map<String, String> rejectData) {
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "商家已拒绝");
        return ResponseEntity.ok(response);
    }

    @PutMapping("/admin/merchants/{id}/suspend")
    @Operation(summary = "暂停商家")
    public ResponseEntity<Map<String, Object>> suspendMerchant(
            @PathVariable Long id,
            @RequestBody Map<String, String> suspendData) {
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "商家已暂停");
        return ResponseEntity.ok(response);
    }
}
